package tcm.com.gistone.api.restController;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tcm.com.gistone.api.service.WordService;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.database.entity.Word;
import tcm.com.gistone.util.ClientUtil;
import tcm.com.gistone.util.EdatResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangfan on 2017/8/12.
 */
@RestController("apiWordController")
@RequestMapping("api/word")
public class WordController {


    @Autowired
    private GetBySqlMapper getBySqlMapper;
    @Autowired
    WordService wordService;

    /**
     * 获取主题词信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "getWord", method = RequestMethod.POST)
    public EdatResult getWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            int specialId = data.getInt("specialId");
            String word = data.getString("word");

            String sql = "select word from tb_word where special_id=" + specialId + " and word like \"%" + word + "%\" limit 0,10";
            List<Map> result = getBySqlMapper.findRecords(sql);
            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /**
     * 获取主题词对应的主题类型
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "getWordType", method = RequestMethod.POST)
    public EdatResult getWordType(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            int wordId = data.getInt("wordId");
            String sql = "select theme_type from tb_word where word_id=" + wordId ;
            List<Map> result = getBySqlMapper.findRecords(sql);
            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /**
     * 检查查询的关键词是否合法
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "checkWord", method = RequestMethod.POST)
    public EdatResult checkWord(HttpServletRequest request, HttpServletResponse response) {
        try {

            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }
            String word = data.getString("word");
            String [] arr =word.split(" ");
            String [] arrNew =new String[arr.length];
            for (int i = 0; i < arr.length; i++) {
                String sql= "select * from tb_word where 1=1";
                if(null!=specialId){
                    sql =sql+" and special_id="+specialId;

                }
                sql =sql+" and word ='"+arr[i]+"'";
                List<Map> result = getBySqlMapper.findRecords(sql);
                if(result.size()>0) {

                    Map wordResult = result.get(0);
                    Long parentId = (Long) wordResult.get("parent_id");
                    Long wordId = (Long) wordResult.get("word_id");
                    if (!parentId.equals(wordId)) {
                        //word存在父亲节点
                        sql = "select * from tb_word where word_id=" + parentId;
                        result = getBySqlMapper.findRecords(sql);
                        String  parentWord =result.get(0).get("word").toString();
                        arrNew[i]=parentWord;

                    }else{
                        arrNew[i]=arr[i];
                    }

                }else{
                    return EdatResult.build(2,"没有与"+arr[i]+"相关的关键词","");
                }

            }
            return EdatResult.ok(arrNew);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /**
     * 根据关键词查询统计信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "queryStatisticsByWord2", method = RequestMethod.POST)
    public EdatResult queryStatisticsByWord2(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }
            String word = data.getString("word");
            System.out.println(word+"-----");

            String [] arr =word.split(" ");
            if(arr.length==1){
                System.out.println("111");
                List<Map> results = wordService.getStatisticsByWord2(specialId, word);
                if (results.size() > 0) {
                    return EdatResult.ok(results);
                } else {
                    return EdatResult.build(2, "no message");
                }

            }else  {

                List<Map> results = wordService.getStatisticsByMutiWord2(specialId,arr[0],arr[1]);
                if (results.size() > 0) {
                    return EdatResult.ok(results);
                } else {
                    return EdatResult.build(2, "no message");
                }

            }



        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }





    /**
     * 根据关键词查询统计信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "queryStatisticsByWord", method = RequestMethod.POST)
    public EdatResult queryStatisticsByWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }
            String word = data.getString("word");

            String [] arr =word.split(" ");
            if(arr.length==1){
                long queryWordId = wordService.getWordIdByWordString(specialId, word);
                if (queryWordId > 0) {
                    List<Map> results = wordService.getStatisticsByWord(specialId, queryWordId);
                    if (results.size() > 0) {
                        return EdatResult.ok(results);
                    } else {
                        return EdatResult.build(2, "no message");
                    }

                } else {
                    return EdatResult.build(2, "no message");
                }
            }else  {
                long queryWordId1 = wordService.getWordIdByWordString(specialId, arr[0]);
                long queryWordId2 = wordService.getWordIdByWordString(specialId, arr[1]);


                List<Map> results = wordService.getStatisticsByMutiWord(specialId,queryWordId1,queryWordId2);
                if (results.size() > 0) {
                    return EdatResult.ok(results);
                } else {
                    return EdatResult.build(2, "no message");
                }

            }



        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /**
     * 根据书id与关键词获取二级信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "queryByBookAndWord", method = RequestMethod.POST)
    public EdatResult queryByBookAndWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer bookId = data.getInt("bookId");
            String word = data.getString("word");
            String[] arr =word.split(" ");
            String sql;
            if(arr.length==1) {

                 sql = "select * from tb_section where book_id =" + bookId + " and section_content like '%" + word + "%' " +
                         "ORDER BY CASE  WHEN section_title LIKE  '%" + word + "%' " +
                         "THEN  section_title ELSE  section_content END DESC ";

            }else{

                sql = "select * from tb_section where book_id =" + bookId + " and section_content like '%" + arr[0]+ "%' "
                        + " and section_content like '%" + arr[1]+ "%' "+
                        " ORDER BY CASE  WHEN section_title LIKE  '%" + arr[0] + "%' and section_title LIKE  '%" + arr[1] + "%' THEN  section_title ELSE  section_content END DESC ";

            }

            List<Map> result = getBySqlMapper.findRecords(sql);

            List<Map> list = new ArrayList<>();

            if (result.size() > 0) {
                for (int i = 0; i < result.size(); i++) {
                    Map item = result.get(i);
//                    String sectionTitle = item.get("section_title").toString().replaceAll(word, "<span class='titleSelective'>" + word + "</span>");
                    String sectionTitle = item.get("section_title").toString();
//                    String sectionContent = item.get("section_content").toString().replaceAll(word, "<span class='selective'>" + word + "</span>");
                    String sectionContent = item.get("section_content").toString();


                    String sectionId = item.get("section_id").toString();

                    String pagenum = item.get("number").toString();


                    Map m = new HashMap();
                    m.put("sectionTitle", sectionTitle);
                    m.put("sectionContent", sectionContent);
                    m.put("sectionId", sectionId);
                    m.put("pagenum", pagenum);

                    list.add(m);
                }
            }
            return EdatResult.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /**
     * 根据关键词获取道地相关信息
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "getHotWord", method = RequestMethod.POST)
    public EdatResult getHotWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String sql="SELECT  DISTINCT c.name  from tb_group_word a ,tb_word b ,tb_ancient_modern_place c WHERE a.word_id=b.word_id and b.special_id=1 and b.word =c.name";
            List<Map> result = getBySqlMapper.findRecords(sql);
            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    @RequestMapping(value = "getHotWordData", method = RequestMethod.POST)
    public EdatResult getHotWordData(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            JSONArray word =  data.getJSONArray("word");

            System.out.println(word.toString());

//            String[] words =word.split(",");
            String wordArr="(";
            for (int i = 0; i < word.size(); i++) {
                String w =word.getString(i);
                if(i==word.size()-1){
                    wordArr = wordArr+"'" + w + "')";
                }else {
                    wordArr = wordArr + "'" + w + "',";
                }

            }
            String sql="SELECT  c.*  from tb_group_word a ,tb_word b ,tb_ancient_modern_place c " +
                    " WHERE a.word_id=b.word_id and b.special_id=1 and b.word =c.name  and c.name" +
                    " in "+wordArr;
            System.out.println(sql);
            List<Map> result = getBySqlMapper.findRecords(sql);
            System.out.println(result.size());
            System.out.println(result.toString());
            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }




    @RequestMapping(value = "queryPlaceByBookAndWord", method = RequestMethod.POST)
    public EdatResult queryPlaceByBookAndWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer bookId = data.getInt("bookId");
            String word = data.getString("word");
            String[] arr =word.split(" ");
            String str;

            List<Map>  result = new ArrayList<>();
            if(arr.length==1){
                Map  m =wordService.queryPlaceByBookAndWord(bookId,word);
                result.add(m);

            }else {
                Map m1=wordService.queryPlaceByBookAndWord(bookId,arr[0]);
                Map m2=wordService.queryPlaceByBookAndWord(bookId,arr[1]);
                result.add(m1);
                result.add(m2);


//               if(str1.isEmpty()){
//                   if(str2.isEmpty()){
//                       str = "";
//
//                   }else{
//                       str = str2;
//                   }
//
//
//                }else{
//                   if(str2.isEmpty()){
//                       str = str1;
//                   }else{
//                       str = str1+"、"+str2;
//                   }
//               }

            }


            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }


    @RequestMapping(value = "queryWordByType", method = RequestMethod.POST)
    public EdatResult queryWordByType(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }
            Integer typeId = data.getInt("typeId");


            System.out.println(typeId);
            String sql = "select DISTINCT c.word from tb_word_group a,tb_group_word b ,tb_word c WHERE a.group_name=b.group_name and b.word_id=c.word_id and b.type_name=a.type_name  and a.type_id="+typeId;

            if(null!=specialId){
                sql=sql+" and a.special_id="+specialId;
            }
            List<Map> result = getBySqlMapper.findRecords(sql);
            return EdatResult.ok(result);


        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }
    /**
     * 根据关键词查询所有信息，提供下载的时候使用
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "queryAllByWord", method = RequestMethod.POST)
    public EdatResult queryAllByWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }
            String word = data.getString("word");
            long queryWordId = wordService.getWordIdByWordString(specialId, word);
            List<Map> allResults =new ArrayList<>();

            if (queryWordId > 0) {

                List<Map> bookList = wordService.getStatisticsByWord(specialId, queryWordId);

                if (bookList.size() > 0) {

                    for (int i = 0; i < bookList.size(); i++) {
                        long bookId=(long)bookList.get(i).get("book_id");
                        Map m=bookList.get(i);
                        List<Map> sectionList =wordService.getListByWordAndBookId(word,bookId);
                        m.put("sectionList",sectionList);
                        allResults.add(m);
                    }



                    return EdatResult.ok(allResults);
                } else {
                    return EdatResult.build(2, "no message");
                }


            } else {
                return EdatResult.build(2, "no message");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }



}
